package com.aacar.service.impl;

import com.alipay.config.AlipayConfig;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aacar.constant.ConsFiled;
import com.aacar.dao.*;
import com.aacar.dto.MemberOrderListDto;
import com.aacar.dto.SmsDto;
import com.aacar.dto.SubmitOrderDto;
import com.aacar.entity.*;
import com.aacar.interceptor.TranFailException;
import com.aacar.service.MemberOrderService;
import com.aacar.service.SeqService;
import com.aacar.utils.*;
import com.aacar.utils.message.SmSUtils;
import com.aacar.vo.MemberOrderDetailVo;
import com.aacar.vo.MemberOrderListVo;
import com.aacar.vo.SubmitOrderVo;
import com.aacar.vo.UserInfoVo;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.util.StringUtil;
import org.springframework.stereotype.Repository;
import push.PushUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository("memberOrderService")
public class MemberOrderServiceImpl implements MemberOrderService {

	private Log logger = LogFactory.getLog(MemberOrderServiceImpl.class);

	@Resource
	private OrderDao orderDao;

	@Resource
	private OrderDemandDao orderDemandDao;

	@Resource
	private OrderPayDao orderPayDao;

	@Resource
	private SeqService seqService;

	@Resource
	private MemberOrderDao memberOrderDao;

	@Resource
	private MemberDao memberDao;

	@Resource
	private CouponDao couponDao;

	@Resource
	private UserIntegralPayDao userIntegralPayDao;

	private boolean isEmpty(String str){
		if(str!=null&&!"".equals(str)){
			return false;
		}else{
			return true;
		}

	}

	@Override
	public SubmitOrderVo submitOrder(SubmitOrderDto submitOrderDto) {

		//生成订单编号
		String orderNo = seqService.getSeqNoFromMem("0", 1);

		//校验车相关
        if(isEmpty(submitOrderDto.getBrandName())||isEmpty(submitOrderDto.getSeriesName())){
			throw new TranFailException(ErrorCodeConsField.ERROR_MSG_42006, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_42006));
		}

		//校验地址相关
		if(isEmpty(submitOrderDto.getProvinceName())||isEmpty(submitOrderDto.getCityName())
				||isEmpty(submitOrderDto.getAreaName())||isEmpty(submitOrderDto.getDetailAddress())||isEmpty(submitOrderDto.getRoomName())){
			throw new TranFailException(ErrorCodeConsField.ERROR_MSG_42007, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_42007));
		}

		//校验时间相关
		if(submitOrderDto.getBookStartTime()==null||submitOrderDto.getBookEndTime()==null){
			throw new TranFailException(ErrorCodeConsField.ERROR_MSG_42008, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_42008));
		}



		//if (预约单）
		//校验 如果预约起始时间小于当前系统时间

		//校验 预约单时间 7:00~23:50 最晚时间 20：50 - 23：50

		//校验 判断两个小于50分钟 是预约单
		//}

		//校验 及时单 7:00~23:00 最晚时间 21：00 - 23：00



		Date now = DateUtil.getNowDate();

		// 校验产品ID
		// 判断 有没有"enjoyPrice": 9.9  //尊享价格 而且最终的产品价格和尊享价格一直 就不让他使用优惠券

		//校验产品价格和会员价格不能为0
		if(submitOrderDto.getProductPrice()==0||submitOrderDto.getUserRankPrice()==0){
			throw new TranFailException(ErrorCodeConsField.ERROR_MSG_42005, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_42005));

		}



		// 校验优惠券 优惠券改为已使用
		double couponAmount = 0.0;
		if (submitOrderDto.getCouponNo() != null && !"".equals(submitOrderDto.getCouponNo())) {

//			Coupon coupon = couponDao.getCoupon(submitOrderDto.getCouponNo());
			Coupon coupon = null;
			
			if (CouponServiceImpl.COUPON_FREE_FOR_1ST.equals(submitOrderDto.getCouponNo())) {
				coupon = couponDao.get1stAvailableCoupon();
			} else {
				coupon = couponDao.getCoupon(submitOrderDto.getCouponNo());
			}

			//优惠券号不存在
			if (coupon == null) {
				throw new TranFailException(ErrorCodeConsField.ERROR_MSG_42001, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_42001));
			}

			if (coupon.getCouponAmount() != submitOrderDto.getCouponAmount()) {
				//优惠券金额不符
				throw new TranFailException(ErrorCodeConsField.ERROR_MSG_42002, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_42002));

			} else if (coupon.getValidEndTime().getTime() < DateUtil.getNowDate().getTime()) {
				//优惠券已过期
				throw new TranFailException(ErrorCodeConsField.ERROR_MSG_42003, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_42003));

			} else if ("2".equals(coupon.getCouponStatus())) {
				//优惠券已使用
				throw new TranFailException(ErrorCodeConsField.ERROR_MSG_42004, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_42004));

			} else {
				if (!CouponServiceImpl.COUPON_FREE_FOR_1ST.equals(submitOrderDto.getCouponNo())) {
					coupon.setCouponNo(submitOrderDto.getCouponNo());
				}
//				coupon.setCouponNo(submitOrderDto.getCouponNo());
				coupon.setCouponStatus("2"); //优惠券状态 2-已使用
				coupon.setIsValid("0"); //0-无效
				coupon.setModifyTime(now);
				couponDao.update(coupon);

			}

			couponAmount = coupon.getCouponAmount();
		}

		Member memParam = new Member();
		memParam.setMemberId(submitOrderDto.getUserId());
		UserInfoVo userInfoVo = memberDao.getUserInfo(memParam);

		// 校验积分 扣除积分
		if (submitOrderDto.getPayIntegral() != 0) {

			if (userInfoVo != null) {
				double submitPayIntegral = MathUtil.disposeAmount(submitOrderDto.getPayIntegral());
				if (Double.valueOf(userInfoVo.getIntegral()) < submitPayIntegral) {
					//积分不够
					throw new TranFailException(ErrorCodeConsField.ERROR_MSG_40009, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_40009));
				} else {
					memParam.setIntegral(MathUtil.disposeAmount(submitPayIntegral));
					memberDao.updateMember(memParam);

					//插入会员积分记录
					Map mapParam = new HashMap();
					mapParam.put("orderNo", orderNo);
					mapParam.put("type", "2");
					mapParam.put("amount", -submitPayIntegral);
					mapParam.put("createTime", now);
					mapParam.put("userId", submitOrderDto.getUserId());
					userIntegralPayDao.saveRecods(mapParam);
				}

			}
		}



		//插入主订单
		Order order = new Order();
		BeanUtil.copyProperties(submitOrderDto, order);
		order.setOrderNo(orderNo);
		order.setOrderAmount(submitOrderDto.getResultProductPrice());
		order.setOrderStatus("R01");
		order.setOrderStatusName("待支付");
		order.setOrderSubStatus("R01");
		order.setWashType(submitOrderDto.getWashType());
		orderDao.save(order);

		//插入需求订单
		OrderDemand orderDemand = new OrderDemand();
		orderDemand.setOrderNo(orderNo);
		orderDemand.setDeOrderNo("DE" + orderNo);
		orderDemand.setDiscAmount(MathUtil.disposeAmount(submitOrderDto.getProductPrice() - submitOrderDto.getResultProductPrice()));
		orderDemand.setDemandStatus("DE01"); //需求状态（DE01-已提交, DE02-待匹配, DE03-已匹配，DE04-已取消)
		orderDemand.setDemandSubStatus("DE01"); //需求子状态（DE01-已提交, DE02-待匹配, DE0301-系统匹配, DE0302-人工匹配, DE0401-客户取消，DE0402-系统人工取消，DE0403-系统自动取消)
		BeanUtil.copyProperties(submitOrderDto, orderDemand);
		orderDemandDao.save(orderDemand);

		//插入支付订单
		OrderPay orderPay = new OrderPay();
		BeanUtil.copyProperties(submitOrderDto, orderPay);
		orderPay.setOrderNo(orderNo);
		String payOrderNo = "PA" + orderNo + "-1";
		orderPay.setCouponAmount(couponAmount);
		orderPay.setPayOrderNo(payOrderNo);
		orderPay.setPayOrderType("1");
		orderPay.setPayStatus("PA01"); //支付状态(PA01-待支付，PA02-已支付 ,PA03-已取消)
		orderPay.setPaySubStatus("PA01"); //支付子状态(PA01-待支付，PA0201-支付成功  ,PA0202-支付失败， PA0301-客户取消，PA0302-系统人工取消，PA0303-系统自动取消)
		orderPay.setPayIntegralRate(1.0);
		orderPay.setPayIntegralAmt(MathUtil.disposeAmount(orderPay.getPayIntegral() * orderPay.getPayIntegralRate()));
		orderPay.setOrderAmount(submitOrderDto.getResultProductPrice());

		//当用户等级为银牌会员时 用户信息的是否首单为 "0"
		if("2".equals(userInfoVo.getRankId())) {
			Member memParam2 = new Member();
			memParam2.setIsFirstOrder("0");
			memParam2.setMemberId(submitOrderDto.getUserId());
			memberDao.updateMember(memParam2);
		}


		//计算支付金额
		//payAmount不能为负数
		double payAmount = MathUtil.disposeAmount(orderPay.getOrderAmount()
				- couponAmount - orderPay.getPayIntegralAmt());
		payAmount = payAmount < 0.0 ? 0.0 : payAmount;
		if (payAmount != submitOrderDto.getPayAmount()) {
			//支付金额不否
			throw new TranFailException(ErrorCodeConsField.ERROR_MSG_41002, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_41002));

		} else {
			orderPay.setPayAmount(payAmount);
			orderPayDao.save(orderPay);
		}



		SubmitOrderVo submitorderVo = new SubmitOrderVo();
		submitorderVo.setOrderNo(orderNo);
		//支付金额为0 （如果积分够付 就直接返回状态 不用 已付款状态标识（不用在呼支付宝了））
		if (payAmount <= 0) {

			submitorderVo.setPayFlag("success");

			//修改支付订单状态为已支付 子状态为积分优惠券支付
			OrderPay orderPayParam = new OrderPay();
			orderPayParam.setPayStatus("PA02");
			orderPayParam.setPaySubStatus("PA0202");
			orderPayParam.setPayOrderNo(payOrderNo);
			orderPayParam.setModifyTime(now);
			orderPayDao.update(orderPayParam);

			//修改主订单状态为 等待接单
			Order orderParam = new Order();
			orderParam.setOrderStatus("R02");
			orderParam.setOrderStatusName("等待接单");
			orderParam.setOrderSubStatus("R02");
			orderParam.setOrderNo(orderNo);
			orderParam.setModifyTime(now);
			orderDao.update(orderParam);

			// 修改需求订单状态为 待匹配
			OrderDemand orderDemandParam = new OrderDemand();
			orderDemandParam.setDemandStatus("DE02");//需求状态（DE01-已提交, DE02-待匹配, DE03-已匹配，DE04-已取消)
			orderDemandParam.setDemandSubStatus("DE02");//需求子状态（DE01-已提交, DE02-待匹配, DE0301-系统匹配, DE0302-人工匹配, DE0401-客户取消，DE0402-系统人工取消，DE0403-系统自动取消)
			orderDemandParam.setOrderNo(orderNo);
			orderDemandParam.setModifyTime(now);
			orderDemandDao.update(orderDemandParam);

		} else {
			submitorderVo.setPayFlag("none");

		}

		//推送
		String pusMsg = "none".equals(submitorderVo.getPayFlag())?"已提交":"已支付";
		PushUtils.sendAndroidAndIOSUnicast(userInfoVo.getDeviceType(),userInfoVo.getDeviceTokens(),"您尾号为"+orderNo.substring(16)+"的订单("+pusMsg+")", orderNo);
		if ("success".equals(submitorderVo.getPayFlag())) {
			SmsDto smsDto = new SmsDto();
	        smsDto.setOrderNo(orderNo.substring(16));
	        smsDto.setPhoneNo(userInfoVo.getPhoneNo());
			try {
				SendSmsResponse response = 
								SmSUtils.sendSms(
								                 "18117518169", 
								                 ConsFiled.ORDER_IS_PAYED_SMS_TEMPALATE, 
								                 JSON.toJSONString(smsDto));
			}
			catch (ClientException e) {
				String message = String.format("FAILED to send out notification to operator for order {%s}", smsDto.getOrderNo());
				logger.error(message, e);
			}
		}
		return submitorderVo;
	}

	@Override
	public Pagination<MemberOrderListVo> getMemberOrderListPage(MemberOrderListDto memberOrderListDto) {
		Pagination<MemberOrderListVo> pagination = new Pagination<MemberOrderListVo>();
		Page page = memberOrderDao.getMemberOrderListCount(memberOrderListDto);
		page.setPageNumber(memberOrderListDto.getPageNumber());
		page.setPageSize(memberOrderListDto.getPageSize());
		memberOrderListDto.setStartRs(page.getStartRs());
		List<MemberOrderListVo> resultlist = memberOrderDao.getMemberOrderListPage(memberOrderListDto);
		for (MemberOrderListVo memberOrderListVo : resultlist) {
			if (memberOrderListVo.getDiscAmount() > memberOrderListVo.getProductPrice()) {
				memberOrderListVo.setDiscAmount(memberOrderListVo.getProductPrice());
			}

		}
		pagination.setPage(page);
		pagination.setResultList(resultlist);
		return pagination;
	}

	@Override
	public MemberOrderDetailVo getMemberOrderDetail(String orderNo) {
		// to do
		// 如果是补差价状态需要处理返回的详情不一样
		// to do 订单详情 显示 最终产品价格 和 优惠价格（最终产品的优惠+优惠券的金额）
		// 如果优惠券的金额大于等于 产品价格 优惠价格 = 产品价格
		MemberOrderDetailVo memberOrderDetailVo = memberOrderDao.getMemberOrderDetail(orderNo);
		if (memberOrderDetailVo.getDiscAmount() > memberOrderDetailVo.getProductPrice()) {
			memberOrderDetailVo.setDiscAmount(memberOrderDetailVo.getProductPrice());
		}
		if(memberOrderDetailVo.getWasherHeadUrl()!=null&& !"".equals(memberOrderDetailVo.getWasherHeadUrl())) {
			memberOrderDetailVo.setWasherHeadUrl(CommonStaticPath.washerHeadUrlPath + memberOrderDetailVo.getWasherHeadUrl());
		}
		return memberOrderDetailVo;
	}

	@Override
	public String cancelMemberOrder(String orderNo,Long userId,String deviceTokens) {
		Date now = DateUtil.getNowDate();
		//查询当前订单的状态
		Order order = orderDao.getOrder(orderNo);
		OrderPay orderPay = orderPayDao.getOrderPay("PA" + orderNo + "-1");
		if (order == null||orderPay.getUserId()!=userId) {
			//用户订单编号不存在
			throw new TranFailException(ErrorCodeConsField.ERROR_MSG_41001, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_41001));
		} else {
			if ("R01".equals(order.getOrderStatus()) || "R02".equals(order.getOrderStatus())) {
				//修改主订单状态 为已取消
				order.setOrderStatus("R08");
				order.setOrderStatusName("已取消");
				order.setOrderSubStatus("R0801"); //客户取消
				order.setModifyTime(now);
				orderDao.update(order);
				//修改需求订单状态 为已取消 DE04
				OrderDemand orderDemand = new OrderDemand();
				orderDemand.setOrderNo(orderNo);
				orderDemand.setDemandStatus("DE04");
				orderDemand.setDemandSubStatus("DE0401");
				orderDemand.setModifyTime(now);
				orderDemandDao.update(orderDemand);
				//修改支付订单状态 为已取消
				orderPay.setPayStatus("PA03");
				orderPay.setPaySubStatus("PA0301");
				orderPay.setModifyTime(now);
				//记录退款金额 退款状态
				if(orderPay.getPayAmount()!=0&&orderPay.getThirdPayCallBackStr()!=null){
					orderPay.setRefundAmount(orderPay.getPayAmount());
					orderPay.setRefundStatus("1"); //退款中
					orderPay.setRefundTime(now);
				}
				orderPayDao.update(orderPay);

				//退还积分
				if (orderPay.getPayIntegral() != 0) {
					Member memParam = new Member();
					memParam.setMemberId(orderPay.getUserId());
					memParam.setIntegral(MathUtil.disposeAmount(-orderPay.getPayIntegral()));
					memParam.setModifyTime(now);
					memParam.setRankId("");
					memParam.setRankName("");
					memberDao.updateMember(memParam);

					//插入会员积分记录
					Map mapParam = new HashMap();
					mapParam.put("orderNo", orderNo);
					mapParam.put("type", "3");
					mapParam.put("amount", orderPay.getPayIntegral());
					mapParam.put("createTime", now);
					mapParam.put("userId", userId);
					userIntegralPayDao.saveRecods(mapParam);
				}

				//退还优惠券
				if (orderPay.getCouponNo()!=null && !"".equals(orderPay.getCouponNo())) {
					Coupon couponParam = new Coupon();
					couponParam.setCouponNo(orderPay.getCouponNo());
					couponParam.setCouponStatus("1"); //优惠券状态 2-已使用
					couponParam.setIsValid("1"); //0-无效
					couponParam.setModifyTime(now);
					couponDao.update(couponParam);
				}


				//只有下单用户的银牌会员是 退换首单 查询该订单对应的用户是否有除了取消以外的订单 如果有 不退首单状态
				if("2".equals(order.getUserRankId())) {
					logger.info("########## 查询该订单对应的用户（下单时为银牌会员）是否有除了取消以外的订单");
					int notCancelOrderCount = orderDao.findNotCancelCount(orderPay.getUserId());
					if (notCancelOrderCount == 0) {
						//退首单状态
						logger.info("########## 退还首单状态");
						Member param = new Member();
						param.setMemberId(orderPay.getUserId());
						param.setIsFirstOrder("1");
						memberDao.updateMember(param);

					}
				}



//				if ("R0201".equals(orderPay.getPaySubStatus()) && "1".equals(orderPay.getPayType())) {
//					//支付宝退款
//					AlipayTradeRefundResponse alipayTradeRefundResponse = alipayTradeRefund(orderPay.getPayOrderNo(),
//							orderPay.getThirdTradeNo(),orderPay.getPayAmount());
//
//				} else if ("R0201".equals(orderPay.getPaySubStatus()) && "2".equals(orderPay.getPayType())) {
//					//微信退款
//				}

			} else {
				//订单不能取消
				throw new TranFailException(ErrorCodeConsField.ERROR_MSG_41003, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_41003));
			}


			//推送消息
			Member memParam2 = new Member();
			memParam2.setMemberId(orderPay.getUserId());
			UserInfoVo userInfoVo = memberDao.getUserInfo(memParam2);
			PushUtils.sendAndroidAndIOSUnicast(userInfoVo.getDeviceType(),userInfoVo.getDeviceTokens(),"您尾号为"+orderNo.substring(16)+"的订单(已取消)", orderNo);

		}

		return "success";

	}

	//支付宝退款
	private AlipayTradeRefundResponse alipayTradeRefund(String orderPayNo,String tradeNo, double refundAmount) {

		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
				AlipayConfig.app_id, AlipayConfig.private_key, "json",
				AlipayConfig.input_charset, AlipayConfig.ali_public_key, "RSA2");


		AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
		AlipayTradeRefundModel model = new AlipayTradeRefundModel();
		model.setOutTradeNo(orderPayNo);
		model.setTradeNo(tradeNo);
		model.setRefundAmount(String.valueOf(refundAmount));

//		request.setBizContent("{"+
//				"\"out_trade_no\":\"20150320010101001\","+
//				"\"trade_no\":\"2014112611001004680073956707\","+
//				"\"refund_amount\":200.12,"+
//				"\"refund_currency\":\"USD\","+
//				"\"refund_reason\":\"正常退款\","+
//				"\"out_request_no\":\"HZ01RF001\","+
//				"\"operator_id\":\"OP001\","+
//				"\"store_id\":\"NJ_S_001\","+
//				"\"terminal_id\":\"NJ_T_001\","+
//				"      \"goods_detail\":[{"+
//				"        \"goods_id\":\"apple-01\","+
//				"\"alipay_goods_id\":\"20010001\","+
//				"\"goods_name\":\"ipad\","+
//				"\"quantity\":1,"+
//				"\"price\":2000,"+
//				"\"goods_category\":\"34543238\","+
//				"\"body\":\"特价手机\","+
//				"\"show_url\":\"http://www.alipay.com/xxx.jpg\""+
//				"        }]"+
//				"  }");
//	AlipayTradeRefundResponse response = alipayClient.execute(request);
//	if(response.isSuccess())
//
//	{
//		System.out.println("调用成功");
//	} else
//
//	{
//		System.out.println("调用失败");
//	}
		return null;
	}

}